package scatter.wxminiapp.rest.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;
import scatter.common.LoginUser;
import scatter.wxminiapp.pojo.form.WxMaUserPhoneNoInfoForm;
import scatter.wxminiapp.pojo.login.WxMaLoginUser;
import scatter.wxminiapp.rest.WxMiniappConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
import scatter.common.rest.controller.BaseAddUpdateQueryFormController;
import scatter.wxminiapp.pojo.po.WxMaUser;
import scatter.wxminiapp.pojo.vo.WxMaUserVo;
import scatter.wxminiapp.pojo.form.WxMaUserAddForm;
import scatter.wxminiapp.pojo.form.WxMaUserUpdateForm;
import scatter.wxminiapp.pojo.form.WxMaUserPageQueryForm;
import scatter.wxminiapp.rest.basic.config.CustomWxMaServiceImpl;
import scatter.wxminiapp.rest.componentext.WxMiniPhoneNoInfoListener;
import scatter.wxminiapp.rest.componentext.WxMiniSessionKeyResolver;
import scatter.wxminiapp.rest.service.IWxMaUserService;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
/**
 * <p>
 * 小程序微信用户表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2021-11-23
 */
@Api(tags = "小程序微信用户相关接口")
@RestController
@RequestMapping(WxMiniappConfiguration.CONTROLLER_BASE_PATH + "/wx-ma-user")
public class WxMaUserController extends BaseAddUpdateQueryFormController<WxMaUser, WxMaUserVo, WxMaUserAddForm, WxMaUserUpdateForm, WxMaUserPageQueryForm> {
    @Autowired
    private IWxMaUserService iWxMaUserService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired(required = false)
    List<WxMiniPhoneNoInfoListener> wxMiniPhoneNoInfoListeners;

    @Autowired
    protected WxMiniSessionKeyResolver wxMiniSessionKeyResolver;

    @ApiOperation("添加小程序微信用户")
    @PreAuthorize("hasAuthority('WxMaUser:add')")
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Override
    public WxMaUserVo add(@RequestBody @Valid WxMaUserAddForm addForm) {
        return super.add(addForm);
    }
    @ApiOperation("根据ID查询小程序微信用户")
    @PreAuthorize("hasAuthority('WxMaUser:queryById')")
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public WxMaUserVo queryById(@PathVariable String id) {
        return super.queryById(id);
    }

    @ApiOperation("根据ID删除小程序微信用户")
    @PreAuthorize("hasAuthority('WxMaUser:deleteById')")
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Override
    public boolean deleteById(@PathVariable String id) {
        return super.deleteById(id);
    }

    @ApiOperation("根据ID更新小程序微信用户")
    @PreAuthorize("hasAuthority('WxMaUser:update')")
    @PutMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Override
    public WxMaUserVo update(@RequestBody @Valid WxMaUserUpdateForm updateForm) {
        return super.update(updateForm);
    }

    @ApiOperation("不分页查询小程序微信用户")
    @PreAuthorize("hasAuthority('WxMaUser:getList')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public List<WxMaUserVo> getList(WxMaUserPageQueryForm listPageForm) {
         return super.getList(listPageForm);
    }

    @ApiOperation("分页查询小程序微信用户")
    @PreAuthorize("hasAuthority('WxMaUser:getPage')")
    @GetMapping("/getPage")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public IPage<WxMaUserVo> getPage(WxMaUserPageQueryForm listPageForm) {
         return super.getPage(listPageForm);
    }

    @ApiOperation(value = "获取微信用户手机号，code方式",notes = "返回同微信开发文档手机号部分 phone_info json")
    @PreAuthorize("user")
    @PostMapping("/phoneNoInfo-by-code/{code}")
    @ResponseStatus(HttpStatus.OK)
    public WxMaPhoneNumberInfo getPhoneNoInfo(@RequestBody WxMaUserPhoneNoInfoForm form, LoginUser loginUser) throws WxErrorException {
        wxMaService.switchoverTo(form.getAppCode());
        WxMaPhoneNumberInfo phoneNoInfo = ((CustomWxMaServiceImpl) wxMaService).getPhoneNoInfo(form.getCode());
        if (wxMiniPhoneNoInfoListeners != null) {
            for (WxMiniPhoneNoInfoListener wxMiniPhoneNoInfoListener : wxMiniPhoneNoInfoListeners) {
                wxMiniPhoneNoInfoListener.phoneNoInfoReady(phoneNoInfo, loginUser);
            }
        }
        return phoneNoInfo;
    }

    @ApiOperation(value = "获取微信用户手机号，解密方式",notes = "返回同微信开发文档手机号部分phone_info json")
    @PreAuthorize("user")
    @PostMapping("/phoneNoInfo-by-code")
    @ResponseStatus(HttpStatus.OK)
    public WxMaPhoneNumberInfo getPhoneNoInfo(@RequestBody WxMaUserPhoneNoInfoForm form, WxMaLoginUser loginUser) {

        String resolveSessionKey = wxMiniSessionKeyResolver.resolveSessionKey(form.getAppCode(), loginUser);
        wxMaService.switchoverTo(form.getAppCode());
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(resolveSessionKey, form.getEncryptedData(), form.getIv());
        if (wxMiniPhoneNoInfoListeners != null) {
            for (WxMiniPhoneNoInfoListener wxMiniPhoneNoInfoListener : wxMiniPhoneNoInfoListeners) {
                wxMiniPhoneNoInfoListener.phoneNoInfoReady(phoneNoInfo, loginUser);
            }
        }
        return phoneNoInfo;
    }
}
